<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                           |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Activity;

use AuctionCore\Common\PhpRedis;
use AuctionCore\Common\Util;
use AuctionCore\Account;
use AuctionCore\Account\FrontUser;

/**
 * 车来车往开奖活动
 *
 * @author Xmh
 */
class Lottory
{

    private $LottoryModel;
    private $LottoryTicketModel;
    private $MyLottoryModel;

    public function __construct()
    {
        $this->LottoryModel = M('lottory');
        $this->LottoryTicketModel = M('lottory_ticket');
        $this->MyLottoryModel = M('my_lottory');
    }

    /**
     * 获取当前是否有活动，有则返回活动ID，无则返回0
     */
    public function is_lottory_online()
    {
        $condition['lottory_status'] = 2;
        $condition['lottory_type'] = 1;
        $condition['lottory_start_time'] = ['elt', date("Y-m-d H:i:s")];
        $condition['lottory_end_time'] = ['egt', date("Y-m-d H:i:s")];
        $lottery_list = $this->LottoryModel->where($condition)->select();
        if (!empty($lottery_list)) {
            return $lottery_list;
        } else {
            $lot_id = 0;
        }
        return $lot_id;
    }

    /**
     * 发送抽奖券
     * @param $uid
     * @param $in_code
     * @return boolean
     */
    public function send_lottery_ticket($uid, $in_code)
    {
        $lottery_list = $this->is_lottory_online();

        if (empty($lottery_list)) {
            return false;
        }

        foreach ($lottery_list as $item){
            $redis = new PhpRedis();
            $keyName = getRedisKeyByCode('REDIS_KEY','100022');
            $res = $redis->rPush($keyName, json_encode([
                'uid' => $uid,
                'lot_id' => $item['id'],
                'invite_code' => $in_code]
            ));
        }
        return $res;
    }

    /**
     * 执行开奖操作
     * @param int $lot_id
     * @param float $sse
     * @param float $szs
     * @param int $lottory_win_num
     * @return bool
     */
    public function do_run_lottory($lot_id, $sse, $szs, $lottory_win_num)
    {
        if ($lot_id < 1) {
            return false;
        }
        $data['id'] = $lot_id;
        $data['sse'] = $sse;
        $data['szs'] = $szs;
        $data['lottory_win_num'] = $lottory_win_num;
        M()->startTrans();
        $res1 = $this->LottoryModel->save($data);

        $ticket['lot_id'] = ['eq', $lot_id];
        $ticket['lottory_ticket_num'] = ['eq', $lottory_win_num];
        $res2 = $this->LottoryTicketModel->where($ticket)->setField('lottory_ticket_status', '1');

        $ticket_map['lot_id'] = ['eq', $lot_id];
        $ticket_map['lottory_ticket_num'] = ['neq', $lottory_win_num];
        $res3 = $this->LottoryTicketModel->where($ticket_map)->setField('lottory_ticket_status', '2');

        $win_uid = $this->LottoryTicketModel->where($ticket)->getField('uid');
        $my_lottory['lot_id'] = ['eq', $lot_id];
        $my_lottory['uid'] = ['eq', $win_uid];
        $res4 = $this->MyLottoryModel->where($my_lottory)->setField('lot_status', 1);

        $my_lottory_map['lot_id'] = ['eq', $lot_id];
        $my_lottory_map['uid'] = ['neq', $win_uid];
        $res5 = $this->MyLottoryModel->where($my_lottory_map)->setField('lot_status', 2);
        if ($res1 !== false && $res2 !== false && $res3 !== false &&
            $res4 !== false && $res5 !== false
        ) {
            M()->commit();
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 获取开奖活动列表
     * @param int $page
     * @param int $page_size
     * @param array $params
     * @return array
     */
    public static function get_lottory_list($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        /**
         * 搜索条件：1、活动ID 2、名称 3、类型 4、状态 5、开始时间 6、结束时间
         */
        if ($params['lot_id']) {
            $map['l.id'] = ['eq', $params['lot_id']];
        }
        if ($params['lot_name']) {
            $map['l.lottory_name'] = ['LIKE', '%' . $params['lot_name'] . '%'];
        }
        if ($params['lot_type']) {
            $map['l.lottory_type'] = ['eq', $params['lot_type']];
        }
        if ($params['lot_status']) {
            $map['l.lottory_status'] = ['eq', $params['lot_status']];
        }
        if ($params['start_time'] && !$params['end_time']) {
            $where['l.lottory_start_time'] = ['egt', $params['start_time'] . " 00:00:00"];
            $where['l.lottory_end_time'] = ['egt', $params['start_time'] . " 00:00:00"];
            $where['_logic'] = "OR";
             $map['_complex'] = $where;
        }
        if ($params['end_time'] && !$params['start_time']) {
            $where['l.lottory_start_time'] = ['elt', $params['end_time'] . " 23:59:59"];
            $where['l.lottory_end_time'] = ['elt', $params['end_time'] . " 23:59:59"];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        if ($params['start_time'] && $params['end_time']) {
            $where['l.lottory_start_time'] = [['egt', $params['start_time'] . " 00:00:00"],['elt', $params['end_time'] . " 23:59:59"],'AND'];
            $where['l.lottory_end_time'] = [['egt', $params['start_time'] . " 00:00:00"],['elt', $params['end_time'] . " 23:59:59"],'AND'];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        //查询历史活动列表 - 进行中和正常结束
        if ($params['his_lottory']) {
            $map['l.lottory_status'] = [['eq', 2], ['eq', 3], 'OR'];
        }
        //已开奖
        if ($params['history_lottory']) {
            $map['l.lottory_status'] = ['eq', 3];
            $map['l.lottory_win_num'] = ['gt', 0];
        }
        $cols = "l.id,l.lottory_name,l.lottory_image,l.lottory_type,l.lottory_award,l.lottory_win_num,
                 l.lottory_start_time,l.lottory_end_time,l.lottory_time,l.lottory_status,l.create_time";
        $order = "l.id DESC";
//        $prefix = C('DB_PREFIX');
        $total = M('lottory')->alias('l')->where($map)->count();
        $list = M('lottory')->alias("l")->field($cols)
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        foreach ($list as $k => $v) {
            $list[$k]['lottory_ticket_nums'] = self::get_lottory_ticket_num($v['id']);
        }
        $result = array(
            'list' => $list,
            'total' => $total,
        );
        return $result;
    }

    /**
     * 获得历史活动列表 - 已结束并开奖
     */
    public function get_history_lottory_list($params,$limit = '')
    {
        $map = [];
        if ($params['lottory_status']) {
            $map['l.lottory_status'] = ['eq', $params['lottory_status']];
        }
        $map['l.lottory_win_num'] = ['gt', 0];
        $cols = "l.id,l.lottory_name,l.lottory_image,l.lottory_type,l.lottory_award,l.lottory_win_num,
                 l.lottory_start_time,l.lottory_end_time,l.lottory_time,l.lottory_status,l.create_time";
        $order = "l.id DESC";
        $list = M('lottory')->alias("l")->field($cols)
            ->where($map)
            ->limit($limit)
            ->order($order)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['lottory_time'] = date("Y年m月d日", strtotime($v['lottory_time']));
            $list[$k]['lottory_cycle'] = date("Y年m月d日", strtotime($v['lottory_start_time'])) . '-'
                . date("Y年m月d日", strtotime($v['lottory_end_time']));

            $win_detail = $this->get_win_detail($v['id'], $v['lottory_win_num']);
            $user = new FrontUser('');
            $info = $user->get_user_info_by_uid($win_detail['uid']);
            $list[$k]['win_user'] = showHideMobile($info['pwd_mobile']);
            $list[$k]['lottory_win_num'] = lottory_ticket_format($v['lottory_win_num']);
            $list[$k]['lottory_ticket_nums'] = self::get_lottory_ticket_num($v['id']);
        }
        return $list;
    }

    /**
     * 获得开奖活动详情
     * @param int $id
     * @return bool|mixed
     */
    public function get_lottory_detail($id = 0)
    {
        if ($id < 1) {
            return false;
        }
        return $this->LottoryModel->find($id);
    }

    /**
     * 创建开奖活动
     * @param array $data
     * @return int
     */
    public function create_lottory($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->LottoryModel->add($data);
    }

    /**
     * 更新开奖活动
     * @param int $lot_id
     * @param array $data
     * @return int
     */
    public function update_lottory($lot_id, $data = [])
    {
        if ($lot_id < 1) {
            return false;
        }
        return $this->LottoryModel->save($data);
    }

    /**
     * 上下线活动操作
     * @param $lot_id
     * @param $lot_status
     * @return bool
     */
    public function update_lottory_status($lot_id, $lot_status)
    {
        $condition['id'] = $lot_id;
        $data['lottory_status'] = $lot_status;
        if ($lot_status == 2) {
            $total = $this->LottoryModel->where($data)->count();
            if ($total > 0) {
                echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 500, 'msg' => '已有活动进行中'));
                exit;
            }
            $now = date("Y-m-d H:i:s");
            $where['lottory_start_time'] =  ['lt',$now];
            $where['lottory_end_time'] =  ['lt',$now];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
            $map['id'] = $lot_id;
            $total_num = $this->LottoryModel->where($map)->count();
            if($total_num){
                echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 500, 'msg' => '活动开始时间已过期'));
                exit;
            }
        }
        return $this->LottoryModel->where($condition)
            ->setField($data);
    }

    /**
     * 更新活动
     * @param array $data
     * @return bool
     */
    public function save_lottory($data = array())
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->LottoryModel->save($data);
    }

    /**
     * 创建活动对应的奖券
     * @param array $data
     * @return boolean|int
     */
    public function create_lottory_ticket($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        $id = $this->LottoryTicketModel->add($data);
        $condition['lot_id'] = $data['lot_id'];
        $condition['id'] = $id;
        $ticket_num = $this->LottoryTicketModel->where($condition)->max('lottory_ticket_num');
        $this->LottoryTicketModel->where($condition)->setField(array('lottory_ticket_num' => $ticket_num));
    }

    /**
     * 获取开奖活动对应的奖券列表
     * @param $page
     * @param $page_size
     * @param $params
     * @return array
     */
    public static function get_lottory_ticket_list($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        /**
         * 搜索条件：
         * 1、奖券ID 2、奖券类型 3、个人ID 4、帐号 5、邀请人ID
         * 6、开奖情况：1、已中奖 2、未中奖 7、开始时间 8、结束时间
         */
        if ($params['lot_id']) {
            $map['lt.lot_id'] = ['eq', $params['lot_id']];
        }
        if ($params['lt_num']) {
            $lt_num = preg_replace('/^0+/', '', trim($params['lt_num']));
            $map['lt.lottory_ticket_num'] = ['LIKE', '%' . $lt_num . '%'];
        }
        if ($params['lt_type']) {
            $map['lt.lottory_ticket_comefrom'] = ['eq', $params['lt_type']];
        }
        if ($params['lt_uid']) {
            $map['lt.uid'] = ['LIKE', '%' . $params['lt_uid'] . '%'];
        }
        if ($params['lt_phone']) {
            $phone = trim($params['lt_phone']);
            $user = new FrontUser('');
            $info = $user->get_user_info_by_pwd_mobile($phone);
            if (!empty($info)) {
                $map['lt.uid'] = ['eq', $info['uid']];
            } else {
                $map['lt.uid'] = ['eq', 0];
            }
        }
        if ($params['invite_uid']) {
            $map['lt.lottory_ticket_comefrom'] = ['eq',3];
            $map['lt.invite_uid'] = ['LIKE', '%' . $params['invite_uid'] . '%'];
        }
        if ($params['lt_status']) {
            $lt_status = $params['lt_status'];
            if ($lt_status == 1) {
                $map['lt.lottory_ticket_status'] = ['eq', $params['lt_status']];
            } else {
                $map['lt.lottory_ticket_status'] = ['eq', $params['lt_status']];
            }
        }
        if ($params['start_time']) {
            $map['lt.create_time'] = ['egt', $params['start_time'] . ' 00:00:00'];
        }
        if ($params['end_time']) {
            $map['lt.create_time'] = ['elt', $params['end_time'] . ' 23:59:59'];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['lt.create_time'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
        }
        $cols = "l.lottory_win_num,
                 lt.id,lt.lot_id,lt.uid,lt.invite_uid,lt.lottory_ticket_num,lt.lottory_ticket_comefrom,
                 lt.lottory_ticket_status,lt.create_time";
        $order = "lt.id DESC";
        $prefix = C('DB_PREFIX');
        $total = M('lottory_ticket')->alias('lt')
            ->where($map)->count();
        $list = M('lottory_ticket')->alias('lt')->field($cols)
            ->join($prefix . 'lottory as l ON lt.lot_id=l.id')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        foreach ($list as $k => $v) {
            $user = new FrontUser();
            $info = $user->get_user_info_by_uid($v['uid']);
            $list[$k]['user'] = $info['pwd_mobile'];
        }
        $result = array(
            'list' => $list,
            'total' => $total,
        );
        return $result;
    }

    /**
     * 获取活动的奖券数量
     * @param int $lot_id
     * @return bool
     */
    public static function get_lottory_ticket_num($lot_id = 0)
    {
        if ($lot_id < 1) {
            return false;
        }
        $condition['lot_id'] = $lot_id;
        return M('lottory_ticket')->where($condition)->count();
    }

    /**
     * 获取我的开奖活动列表
     * @param $page
     * @param $page_size
     * @param $params
     * @return array
     */
    public function my_lottory_list($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 20 : (int)$page_size;
        $map = [];
        if ($params['uid']) {
            $map['ml.uid'] = ['eq', $params['uid']];
        }
        $map['l.lottory_status'] = [['eq', 2], ['eq', 3], 'OR'];
        $cols = "ml.lot_status,l.id,l.lottory_name,l.lottory_type,l.lottory_time,l.lottory_status";
        $order = 'l.id DESC';
        $prefix = C('DB_PREFIX');
        $total = M('my_lottory')->alias('ml')
            ->join($prefix . 'lottory as l ON ml.lot_id = l.id')
            ->where($map)
            ->count();
        $list = M('my_lottory')->alias('ml')->field($cols)
            ->join($prefix . 'lottory as l ON ml.lot_id = l.id')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
        $list = empty($list) ? [] : $list;
//                echo M()->getLastSql();
        $result = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $list
        );
        return $result;
    }

    /**
     * 获取我的开奖活动对应的奖券列表
     * @param $params
     * @return array|bool
     */
    public function get_my_lottory_ticket_list($params)
    {
        if (empty($params)) {
            return false;
        }
        $map['lt.uid'] = ['eq', $params['uid']];
        $map['l.id'] = ['eq', $params['lot_id']];
        $cols = "l.id,l.lottory_status,lt.id,lt.lot_id,lt.uid,lt.invite_uid,
                lt.lottory_ticket_num,lt.lottory_ticket_comefrom,
                lt.lottory_ticket_status,lt.create_time";
        $order = "lt.id DESC";
        $prefix = C('DB_PREFIX');
        $total = M('lottory_ticket')->alias('lt')
            ->join($prefix . 'lottory as l ON lt.lot_id = l.id')
            ->where($map)->count();
        $list = M('lottory_ticket')->alias('lt')->field($cols)
            ->join($prefix . 'lottory as l ON lt.lot_id = l.id')
            ->where($map)
            ->order($order)
            ->select();
//        echo M()->getLastSql();
        foreach ($list as $k => $v) {
            $comefrom = $v['lottory_ticket_comefrom'];
            $user = new FrontUser('');
            $info = $user->get_user_info_by_uid($v['invite_uid']);
            $list[$k]['user'] = $info['pwd_mobile'];
            if ($comefrom == 1) {
                $ticket_comefrom = '注册成功';    
            } elseif ($comefrom == 2) {
                $invite = $user->get_user_info_by_uid($v['invite_uid']);
                if(!empty($invite)){
                    $ticket_comefrom = showHideMobile($invite['pwd_mobile']).'注册成功'; 
                }else{
                    $ticket_comefrom = '邀请注册成功';
                }
            } elseif ($comefrom == 3) {
                $ticket_comefrom = '受邀注册成功'; 
            }
            $lottory_status = $v['lottory_status'];
            if ($lottory_status == 2) {
                $lottory_status_name = '待开奖';
            } elseif ($lottory_status == 3) {
                $lot_ticket_status = $v['lottory_ticket_status'];
                if ($lot_ticket_status == 1) {
                    $lottory_status_name = '已中奖';
                } elseif ($lot_ticket_status == 2) {
                    $lottory_status_name = '未中奖';
                }else{
                    $lottory_status_name = '待开奖';
                }
            }
            $list[$k]['lot_status'] = $lottory_status_name;
            $list[$k]['ticket_comefrom'] = $ticket_comefrom;
        }
//        echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'total' => $total,
        );
        return $result;
    }

    /**
     * 根据中奖号码获得用户信息
     * @param $lot_id
     * @param $win_num
     * @return mixed
     */
    public function get_win_detail($lot_id, $win_num)
    {
        $condition['lot_id'] = $lot_id;
        $condition['lottory_ticket_num'] = $win_num;
        return M('lottory_ticket')->field('uid')->where($condition)->find();
    }

}
